package org.brdevils.bf2sas.server;

import java.net.InetSocketAddress;

import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.textline.TextLineDecoder;
import org.apache.mina.filter.codec.textline.TextLineEncoder;
import org.apache.mina.transport.socket.SocketConnector;
import org.apache.mina.transport.socket.nio.NioSocketConnector;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ServerConnection {
    final Logger logger = LoggerFactory.getLogger(ServerConnection.class);

    private SocketConnector connector;
    private IoSession session;
    private ReadListener reader;
    
    public ServerConnection(ReadListener reader) {
        this.reader = reader;
    }

    public void connect(String senha) {
        try {
            // Create TCP/IP connector.
            connector = new NioSocketConnector();

            // Set connect timeout.
            connector.setConnectTimeoutMillis(30000);
            connector.setHandler(new TelnetProtocolHandler(reader, senha));
            connector.getFilterChain().addLast(
                    "codec",
                    new ProtocolCodecFilter(new TextLineEncoder(),
                            new TextLineDecoder()));

            // Start communication.
            ConnectFuture cf = connector.connect(new InetSocketAddress(
                    "localhost", 4711));

            // Wait for the connection attempt to be finished.
            cf.await();
            session = cf.getSession();
            //session.getConfig().setIdleTime(IdleStatus.READER_IDLE, 1);
        } catch (InterruptedException e) {
            logger.error("Erro!!", e);
            e.printStackTrace();
        }
    }
    
    public void write (String text) {
        if (session != null && session.isConnected()) {
            session.write(text);
        }
    }
}
